const Customer = require('../models/Customer');
const { Op } = require('sequelize');

// 创建新客户
const createCustomer = async (req, res) => {
  try {
    const { name, gender, phone, birthDate, remark } = req.body.data;
    console.log(req.body.data,'alwjdnw');
    
    // 参数验证
    if (!name || !gender || !phone) {
      return res.status(400).json({
        code: 400,
        message: '姓名、性别和手机号为必填项'
      });
    }

    // 检查手机号是否已存在
    const existingCustomer = await Customer.findOne({ where: { phone } });
    if (existingCustomer) {
      return res.status(400).json({
        code: 400,
        message: '该手机号已被注册'
      });
    }

    // 创建客户
    const customer = await Customer.create({
      name,
      gender,
      phone,
      birthDate,
      remark
    });

    res.status(201).json({
      code: 200,
      message: '客户创建成功',
      data: customer
    });

  } catch (error) {
    console.error('创建客户错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取客户列表
const getCustomers = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, phone } = req.body;
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const where = {};
    if (name) where.name = { [Op.like]: `%${name}%` };
    if (phone) where.phone = { [Op.like]: `%${phone}%` };

    const { count, rows } = await Customer.findAndCountAll({
      where,
      order: [['createdAt', 'DESC']],
      offset,
      limit: pageSize
    });

    res.json({
      code: 200,
      message: '获取客户列表成功',
      data: {
        total: count,
        page,
        pageSize,
        list: rows
      }
    });

  } catch (error) {
    console.error('获取客户列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 更新客户信息
const updateCustomer = async (req, res) => {
  try {
    const { id, name, gender, phone, birthDate, remark } = req.body;

    const customer = await Customer.findByPk(id);
    if (!customer) {
      return res.status(404).json({
        code: 404,
        message: '客户不存在'
      });
    }

    // 如果要更新手机号，检查新手机号是否已被其他客户使用
    if (phone && phone !== customer.phone) {
      const existingCustomer = await Customer.findOne({
        where: {
          phone,
          id: { [Op.ne]: id } // 排除当前客户
        }
      });
      if (existingCustomer) {
        return res.status(400).json({
          code: 400,
          message: '该手机号已被其他客户使用'
        });
      }
    }

    // 更新客户信息
    await customer.update({
      name,
      gender,
      phone,
      birthDate,
      remark
    });

    res.json({
      code: 200,
      message: '客户信息更新成功',
      data: customer
    });

  } catch (error) {
    console.error('更新客户信息错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 删除客户
const deleteCustomer = async (req, res) => {
  try {
    const { id } = req.body;

    const customer = await Customer.findByPk(id);
    if (!customer) {
      return res.status(404).json({
        code: 404,
        message: '客户不存在'
      });
    }

    await customer.destroy(); // 软删除

    res.json({
      code: 200,
      message: '客户删除成功'
    });

  } catch (error) {
    console.error('删除客户错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

// 获取单个客户信息
const getCustomerById = async (req, res) => {
  try {
    const { id } = req.body;

    const customer = await Customer.findByPk(id);
    if (!customer) {
      return res.status(404).json({
        code: 404,
        message: '客户不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取客户信息成功',
      data: customer
    });

  } catch (error) {
    console.error('获取客户信息错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

module.exports = {
  createCustomer,
  getCustomers,
  updateCustomer,
  deleteCustomer,
  getCustomerById
};